//
//  TTFileDown.m
//  WxIOSReaderForiPhone
//
//  Created by anzeinfo on 17-11-14.
//  Copyright (c) 2017年 anzeinfo. All rights reserved.
//

#import "TTFileDown.h"
#import "AFNetworking.h"
#import "TTFileManager.h"

@implementation TTFileDown

+ (TTFileDown *)sharedManager
{
    static TTFileDown *_sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedManager = [[TTFileDown alloc]init];
    });
    return _sharedManager;
}

+ (instancetype)init {
    return [super manager];
}

-(void)downFile:(NSString*)url
       filePath:(NSString*)filePath
       progress:(void(^)(float progress))onDownProgress
       sucessed:(void(^)(void))onSucessed
        failure:(void(^)(void))onFailure{
    //1.覆盖方式，检查同名文件并删除
    if([[TTFileManager sharedManager]fileExists:filePath]){
        [[TTFileManager sharedManager]deleteFile:filePath];
    }
    
    //2.创建URL请求对象
    NSURL *urlObj = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:urlObj];
    //下载任务
    NSURLSessionDownloadTask *task = [self downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        //更新下载进度
        float percentDone = (float)downloadProgress.completedUnitCount / (float)downloadProgress.totalUnitCount;
        dispatch_async(dispatch_get_main_queue(), ^{
            if(onDownProgress != nil){
                onDownProgress(percentDone*100);
            }
        });
        NSLog(@"%%%lf",percentDone*100);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        //设置下载路径，通过沙盒获取缓存地址，最后返回NSURL对象
        NSURL *downloadURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory
                                                                    inDomain:NSUserDomainMask
                                                           appropriateForURL:nil
                                                                      create:NO error:nil];
        downloadURL = [downloadURL URLByAppendingPathComponent:[filePath lastPathComponent]];
        //NSLog(@"下载的临时文件地址:%@",targetPath);
        //NSLog(@"目标文件地址:%@",downloadURL);
        return downloadURL;
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSString *path = [filePath relativePath]; //从URL文件路径转中获取沙盒路径
        if (error) {
            NSLog(@"下载失败，请重试，原因:%@ url:[%@]",url,error);
            //delegate回传下载状态
            dispatch_async(dispatch_get_main_queue(), ^{
                if(onFailure != nil){
                    onFailure();
                }
                if([[TTFileManager sharedManager]fileExists:path]){
                    [[TTFileManager sharedManager]deleteFile:path];
                }
            });
        }else{
            NSLog(@"文件下载完成\n,%@--%@",response,path);
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                if(onSucessed != nil){
                    onSucessed();
                }
            });
        }
    }];
    //开始启动任务
    [task resume];
}
//TaskManager Motheds
-(void)cancel:(NSString *)url{
    for(NSURLSessionDownloadTask *taskTmp in self.downloadTasks){
        if([[taskTmp.currentRequest.URL absoluteString]isEqualToString:url]){
            [taskTmp cancel];
        }
    }
}
-(Boolean)resume:(NSString *)url{
    for(NSURLSessionDownloadTask *taskTmp in self.downloadTasks){
        if([[taskTmp.currentRequest.URL absoluteString]isEqualToString:url]){
            [taskTmp resume];
            return YES;
        }
    }
    return NO;
}
-(Boolean)isExist:(NSString *)url{
    for(NSURLSessionDownloadTask *taskTmp in self.downloadTasks){
        if([[taskTmp.currentRequest.URL absoluteString]isEqualToString:url]){
            return YES;
        }
    }
    return NO;
}
-(int)Count{
    return (int)self.downloadTasks.count;
}
@end
